var t = getApp(),
  e = t.requirejs("core"),
  i = t.requirejs("check");
var running = false;
Page({
  data: {
    id: '',
    posting: false,
    subtext: "保存地址",
    detail: {
      consigner: "",
      phone: "",
      area: "",
      address: "",
      areaid:''
    },
    showPicker: false,
    pvalOld: [0, 0, 0],
    pval: [0, 0, 0],
    areas: [],
    street: [],
    streetIndex: 0,
    noArea: false
  },
  get_wx_address: function () {
    var that = this,
      info = that.data.detail;
    wx.chooseAddress({

      success: function (res) {
        info.consigner = res.userName;
        info.phone = res.telNumber;
        info.address = res.detailInfo;
        info.province = res.provinceName;
        info.city = res.cityName;
        info.area = res.countyName;
        var r = info.province + " " + info.city + " " + info.area,
          s = that.getIndex(r, that.data.areas);
          info.areaid = that.getareaid(r, that.data.areas);
        if (info.areaid==null){
          e.alert('该地址无法自动获取,请手动选择');
         }else{
          that.setData({
            pvalOld: s,
            pval: s,
            detail: info
          });
         }
        
      }
    })
  },
  onLoad: function (ev) {
   // e.setting();
    this.setData({
      id: ev.id,
      type:ev.type,
      order:ev.order,
      config: getApp().config
    });
      this.getDetail();
      ev.id || wx.setNavigationBarTitle({
        title: "添加收货地址"
      });
    var that=this;
    e.get("area/GetArea", {}, function (i) {
      console.log(i)
      that.setData({
        areas: i.areas,
      })
    })
     // console.log(this.data)
  },
/**
* 修改时获取地址详情
*/
  getDetail: function () {
   
    var t = this,
      a = t.data.id;
    e.get("user/SingleAddress", {
      id: a,
      uid: getApp().getCache("userinfo").uid
    }, function (e) {
      var a = {
        //openstreet: e.openstreet,
        show: true
      };
      if (!i.isEmptyObject(e.info)) {
        wx.setNavigationBarTitle({
          title: "编辑收货地址"
        });
        var r = e.info.province + " " + e.info.city + " " + e.info.district,
          s = t.getIndex(r, t.data.areas);
        a.pval = s,
          a.pvalOld = s,
          a.detail=e.info;
        a.detail.area = e.info.district;
        
      }
      t.setData(a)
        // e.openstreet && s && t.getStreet(t.data.areas, s)
    })
  },
/**
* 提交添加/修改收货地址
*/
  submit: function (z) {
    var t = this,
      id = this.data.id,
      q = e.pdata(z).type,
      i = t.data.detail;
    if (running) {
      return;
    }
    
    i.uid = getApp().getCache("userinfo").uid
    if ("" == i.consigner || !i.consigner){
      e.toast("请填写收件人");
      return false;
    }
     
    if ("" == i.phone || !i.phone){
      e.toast("请填写联系电话");
      return false;
    }
    if ("" == i.city || !i.city){
      e.toast("请选择所在地区");
      return false;
    }
    if ("" == i.address || !i.address){
      e.toast("请填写详细地址");
      return false;
    }
    
     
    t.setData({
      posting: true
    });
    running = true;
    if (q == 'add') {
      console.log(i)
      e.get("user/CreateAddress", i, function (i) {
        running = false;
        if (0 != i.code)
          return t.setData({
            posting: false
          }),void e.alert(i.msg);
        e.success("添加成功！"),
          setTimeout(function () {
          "add" == t.data.type && 1==t.data.order ? wx.redirectTo({
              url: "/yb_mingpian/pages/member/address/select"
          }) :wx.navigateBack()  
          }, 1e3)
      })
    } else {
      i.id = id,
          console.log("address",i);
        e.get("user/UpdateAddress", i, function (i) {
        running = false;
          console.log("res",i);
          if (0 != i.code)
            return t.setData({
              posting: false
            }), void e.alert(i.msg);
          e.success("修改成功！"),
            setTimeout(function () {
            "member" == t.data.type && 2 == t.data.order? wx.redirectTo({
              url: "/yb_mingpian/pages/member/address/select"
            }) : wx.navigateBack()  
            }, 1e3)
        })
    }
   
  },

  onChange: function (t) {
    var e = this,
      a = e.data.detail,
      r = t.currentTarget.dataset.type,
      s = i.trim(t.detail.value);
      a[r] = s,
      e.setData({
        detail: a
      })
  },
    /**
* 选择地址
*/
  selectArea: function (t) {
    var e = t.currentTarget.dataset.area;
    //console.log(e)
    var  a = this.getIndex(e, this.data.areas);

      
    this.setData({
      pval: a,
      pvalOld: a,
      showPicker: true
    })
  },
  getStreet: function (t, a) {

    if (t && a) {
      var i = this;
      if (i.data.detail.province && i.data.detail.city && this.data.openstreet) {
        
        var r = t[a[0]].city[a[1]].code,
          s = t[a[0]].city[a[1]].area[a[
            2]].code;
        
      }
    }
  },
  bindChange: function (t) {
    var e = this.data.pvalOld,
      a = t.detail.value;
      //console.log(e)
    e[0] != a[0] && (a[1] = 0),
      e[1] != a[1] && (a[2] = 0),
      this.setData({
        pval: a,
        pvalOld: a
      })
  },
  onCancel: function (t) {
    this.setData({
      showPicker: false
    })
  },
  onConfirm: function (t) {
    var e = this.data.pval,
      a = this.data.areas,
      i = this.data.detail;
    i.province = a[e[0]].name,
      i.city = a[e[0]].city[e[1]].name,
      i.areaid=a[e[0]].city[e[1]].area[e[2]].id,
      i.datavalue = a[e[0]].code + " " + a[e[0]].city[e[1]].code,
      a[e[0]].city[e[1]].area && a[e[0]].city[e[1]].area.length > 0 ? (i.area = a[e[0]].city[e[1]].area[e[2]].name, i.datavalue += " " + a[e[0]].city[e[1]].area[e[2]].code, this.getStreet(a, e)) : i.area = "",
      i.street = "",
      this.setData({
        detail: i,
        streetIndex: 0,
        showPicker: false
      })
  },
/**
* 将地址省市县转换成数组  [0,0,0]格式
*@param  t  某一地址（string）
*@param  e  地址库（array）
return array（[0,0,0]格式）
*/
  getIndex: function (t, e) {

      if ("" == i.trim(t) || !i.isArray(e))
      return [0, 0, 0];
    var a = t.split(" "),
      r = [0, 0, 0];
    for (var s in e)
      if (e[s].name == a[0]) {
        r[0] = Number(s);
        for (var d in e[s].city)
          if (e[s].city[d].name == a[1]) {
            r[1] = Number(d);
            for (var n in e[s].city[d].area)
              if (e[s].city[d].area[n].name == a[2]) {
                r[2] = Number(n);
                break
              }
            break
          }
        break
      }
      console.log(r);
    return r
  },
  getareaid: function (t, e) {
    console.log(t)
    var areaid = null;
    if ("" == i.trim(t) || !i.isArray(e))
      return areaid;
    var a = t.split(" ");
    console.log(e);
    console.log(a);
    for (var s in e)
      if (e[s].name == a[0]) {
        console.log(e[s].city);
        for (var d in e[s].city)
          if (e[s].city[d].name == a[1]) {
            console.log(e[s].city[d].name);
            for (var n in e[s].city[d].area)
              if (e[s].city[d].area[n].name == a[2]) {
                areaid = e[s].city[d].area[n].id;
                break
              }
            break
          }
        break
      }
    console.log(areaid);
    return areaid;
  }
})